#include "Client.h"
#include "Connection.h"
#include <QTcpSocket>
#include <QDebug>

using namespace Networking;
Client::Client(const QString& hostName, quint16 port)
{
    m_conn = connectToServer(hostName, port);

    connect(m_conn.data(), SIGNAL(SignalConnectionLost()),
            this, SLOT(SlotDisconnect()));

    connect(m_conn.data(), SIGNAL(SignalNewMessage(const QString&, int)),
            this, SLOT(SlotProcessMessage(const QString&)));

    connect(this, SIGNAL(SignalSendMessage(const QString&)),
            m_conn.data(), SLOT(SlotSendData(const QString&)));
}

ConnectionPtr Client::connectToServer(const QString& hostName, quint16 port)
{
    qDebug() << "Client::connectToServer(" << hostName << ", " << port << ")";
    QTcpSocket* conn = new QTcpSocket;
    conn->connectToHost(hostName, port);
    return ConnectionPtr(new Connection(conn));
}

//new message from server
void Client::SlotProcessMessage(const QString& msg)
{
    qDebug() << "void Client::SlotProcessMessage(" << msg << ")";
    Command cmd = m_parser->ParseMessage(msg);
    if(cmd.Type() != Command::eUnknown)
        emit SignalNewCommandReady(cmd);
}

void Client::SlotDisconnect()
{
    qDebug() << "Client::SlotDisconnect()";
}
